package com.answer.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.answer.common.ErrorCode;
import com.answer.constant.CommonConstant;
import com.answer.entity.App;
import com.answer.entity.User;
import com.answer.entity.UserAnswer;
import com.answer.mapper.UserAnswerMapper;
import com.answer.model.dto.userAnswer.UserAnswerQueryRequest;
import com.answer.model.vo.UserAnswerVO;
import com.answer.model.vo.UserVO;
import com.answer.service.AppService;
import com.answer.service.UserAnswerService;
import com.answer.service.UserService;
import com.answer.utils.SqlUtils;
import com.answer.utils.ThrowUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户答案服务实现
 */
@Service
@Slf4j
public class UserAnswerServiceImpl extends ServiceImpl<UserAnswerMapper, UserAnswer> implements UserAnswerService {

    @Resource
    private UserService userService;

    @Resource
    private AppService appService;

    /**
     * 校验数据
     * 该方法主要用于校验用户答案对象及其关联应用的合法性它首先检查用户答案对象是否为空，
     * 然后根据是否为新增数据（由add参数决定）执行不同的校验逻辑如果是在新增数据，
     * 它会进一步校验appId的合法性；如果是在修改数据，并且appId存在，则会校验该appId对应的应用是否存在
     *
     * @param userAnswer 用户答案对象，包含用户提交的答案及其关联的应用信息
     * @param add        标识是否为新增数据，用于决定执行新增数据的校验还是修改数据的校验
     */
    @Override
    public void validUserAnswer(UserAnswer userAnswer, boolean add) {
        // 校验用户答案对象是否为空
        ThrowUtils.throwIf(userAnswer == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long appId = userAnswer.getAppId();
        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR, "appId 非法");
        }
        // 修改数据时，有参数则校验
        // 补充校验规则
        if (appId != null) {
            App app = appService.getById(appId);
            // 校验应用是否存在
            ThrowUtils.throwIf(app == null, ErrorCode.PARAMS_ERROR, "应用不存在");
        }
    }

    /**
     * 获取查询条件
     * 根据提供的查询请求对象构建查询包装器，用于数据库查询操作
     *
     * @param userAnswerQueryRequest 用户查询请求对象，包含用户筛选条件
     * @return QueryWrapper<UserAnswer> 包含查询条件的查询包装器对象
     */
    @Override
    public QueryWrapper<UserAnswer> getQueryWrapper(UserAnswerQueryRequest userAnswerQueryRequest) {
        QueryWrapper<UserAnswer> queryWrapper = new QueryWrapper<>();
        if (userAnswerQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = userAnswerQueryRequest.getId();
        Long appId = userAnswerQueryRequest.getAppId();
        Integer appType = userAnswerQueryRequest.getAppType();
        Integer scoringStrategy = userAnswerQueryRequest.getScoringStrategy();
        String choices = userAnswerQueryRequest.getChoices();
        Long resultId = userAnswerQueryRequest.getResultId();
        String resultName = userAnswerQueryRequest.getResultName();
        String resultDesc = userAnswerQueryRequest.getResultDesc();
        String resultPicture = userAnswerQueryRequest.getResultPicture();
        Integer resultScore = userAnswerQueryRequest.getResultScore();
        Long userId = userAnswerQueryRequest.getUserId();
        Long notId = userAnswerQueryRequest.getNotId();
        String searchText = userAnswerQueryRequest.getSearchText();
        String sortField = userAnswerQueryRequest.getSortField();
        String sortOrder = userAnswerQueryRequest.getSortOrder();

        // 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("resultName", searchText).or().like("resultDesc", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(choices), "choices", choices);
        queryWrapper.like(StringUtils.isNotBlank(resultName), "resultName", resultName);
        queryWrapper.like(StringUtils.isNotBlank(resultDesc), "resultDesc", resultDesc);
        queryWrapper.like(StringUtils.isNotBlank(resultPicture), "resultPicture", resultPicture);
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(resultId), "resultId", resultId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(appId), "appId", appId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(appType), "appType", appType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(resultScore), "resultScore", resultScore);
        queryWrapper.eq(ObjectUtils.isNotEmpty(scoringStrategy), "scoringStrategy", scoringStrategy);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取用户答案封装
     *
     * @param userAnswer 用户答案实体对象，用于获取答案详情
     * @return 返回一个UserAnswerVO对象，包含了用户答案的相关信息
     */
    @Override
    public UserAnswerVO getUserAnswerVO(UserAnswer userAnswer) {
        // 将用户答案实体对象转换为用户答案封装对象
        UserAnswerVO userAnswerVO = UserAnswerVO.objToVo(userAnswer);

        // 可以为用户答案封装对象补充额外信息，如用户信息
        // 以下代码段是可选的，根据实际业务需要进行补充或删除
        // 根据用户ID查询用户信息，并将其转换为用户封装对象，然后附加到用户答案封装对象上
        Long userId = userAnswer.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        userAnswerVO.setUser(userVO);
        // 结束可选补充信息

        // 返回填充完毕的用户答案封装对象
        return userAnswerVO;
    }

    /**
     * 分页获取用户答案封装
     *
     * @param userAnswerPage 分页的用户答案数据
     * @return 返回封装后的用户答案分页对象
     */
    @Override
    public Page<UserAnswerVO> getUserAnswerVOPage(Page<UserAnswer> userAnswerPage) {
        // 获取分页数据中的用户答案列表
        List<UserAnswer> userAnswerList = userAnswerPage.getRecords();
        // 创建一个新的分页对象，用于封装转换后的数据
        Page<UserAnswerVO> userAnswerVOPage = new Page<>(userAnswerPage.getCurrent(), userAnswerPage.getSize(), userAnswerPage.getTotal());
        // 如果用户答案列表为空，则直接返回空的分页对象
        if (CollUtil.isEmpty(userAnswerList)) {
            return userAnswerVOPage;
        }
        // 将用户答案实体列表转换为用户答案封装对象列表
        List<UserAnswerVO> userAnswerVOList = userAnswerList.stream().map(UserAnswerVO::objToVo)
                .collect(Collectors.toList());

        // 可选区域：为封装对象补充关联的用户信息等
        // 1. 关联查询用户信息
        Set<Long> userIdSet = userAnswerList.stream().map(UserAnswer::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充用户信息到封装对象中
        userAnswerVOList.forEach(userAnswerVO -> {
            Long userId = userAnswerVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            userAnswerVO.setUser(userService.getUserVO(user));
        });

        // 将处理后的用户答案封装对象列表设置到分页对象中
        userAnswerVOPage.setRecords(userAnswerVOList);
        // 返回封装后的用户答案分页对象
        return userAnswerVOPage;
    }
}
